using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class World : MonoBehaviour
{
    // Start is called before the first frame update
    public Character selfCharacter;
    public Dictionary<string, GameObject> otherCharacters = new Dictionary<string, GameObject>();
    private Dictionary<string, float> _timer = new Dictionary<string, float>(); // 定时删除失活的玩家
    void Start()
    {
        EventMgr.Instance.RegisterEvent(EventType.OnNtfStates, OnNtfStates);
    }

    void OnDestroy()
    {
        EventMgr.Instance.RemoveEvent(EventType.OnNtfStates, OnNtfStates);
    }

    // Update is called once per frame
    void Update()
    {
        foreach (var item in otherCharacters)
        {
            if (!_timer.ContainsKey(item.Key))
            {
                _timer.Add(item.Key, 0);
            }
            _timer[item.Key] = _timer[item.Key] + Time.deltaTime;
            if (_timer[item.Key] > 5)
            {
                Destroy(item.Value);
                otherCharacters.Remove(item.Key);
                _timer.Remove(item.Key);
                break;
            }
        }
    }

    private void OnNtfStates(Message message)
    {
        var data = message.data as SC_NtfStates;
        var states = data.States;
        foreach (PlayerState state in states)
        {
            if (string.IsNullOrEmpty(state.Token))
                continue;
            
            if (state.Token == TCPClient.Instance.token)
                continue;

            _timer.Remove(state.Token);

            if (!otherCharacters.TryGetValue(state.Token, out GameObject character))
            {
                var newInstance = SpawnCharacter(state);
                otherCharacters.Add(state.Token, newInstance);
            }
            else
            {
                character.GetComponent<RemoteController>().ApplyState(state);
            }
        }
    }

    private GameObject SpawnCharacter(PlayerState state)
    {
        var prefab = Resources.Load<GameObject>("Prefabs/Character");
        var instrance = Instantiate(prefab, selfCharacter.transform.parent);
        instrance.transform.SetAsFirstSibling();
        var controller = instrance.AddComponent<RemoteController>();
        controller.ApplyState(state, true);
        return instrance;
    }
}
